<template>
  <div class="products-container">
    <!-- 搜索区域 -->
    <!-- TODO: 搜索功能 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="商品名称" />
        </el-form-item>
        <el-form-item label="价格区间">
          <el-input
            v-model="searchForm.minPrice"
            placeholder="最低价"
            style="width: 100px"
          />
          <span class="mx-2">-</span>
          <el-input
            v-model="searchForm.maxPrice"
            placeholder="最高价"
            style="width: 100px"
          />
        </el-form-item>
        <!-- 新增商品类别下拉列表 -->
        <el-form-item label="商品类别">
          <el-select
            v-model="searchForm.categoryId"
            placeholder="请选择商品类别"
            style="width: 150px;"
          >
            <el-option
              v-for="item in categoryStore.categoryList"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" :icon="Plus" @click="handleAdd"
        >新增商品</el-button
      >
    </div>

    <!-- 商品表格 -->
    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column prop="commodityId" label="商品ID" width="100" />
      <el-table-column label="商品图片" width="120">
        <template #default="{ row }">
          <el-image :src="row.imgUrl[0]" fit="cover" class="avatar" />
        </template>
      </el-table-column>
      <el-table-column prop="commodityTitle" label="商品标题" />
      <el-table-column prop="categoryName" label="商品分类" width="120" />
      <el-table-column label="SKU列表" width="200">
        <template #default="{ row }">
          <el-popover placement="right" :width="400" trigger="click">
            <template #reference>
              <el-button>查看SKU</el-button>
            </template>
            <el-table :data="row.skusDOS" border>
              <!-- TODO: 这里先写死 -->
              <el-table-column prop="specs[0].name" label="单位" />
              <el-table-column prop="specs[0].valueName" label="数量" />
              <el-table-column prop="specs[1].name" label="规格" />
              <el-table-column
                prop="specs[1].valueName"
                label="参数"
                width="300"
              />
              <el-table-column prop="price" label="价格" width="100">
                <template #default="{ row }"> ¥{{ row.price }} </template>
              </el-table-column>
              <el-table-column prop="stock" label="库存" width="100" />
            </el-table>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <!-- 修改按钮 -->
          <el-button
            type="primary"
            :icon="Edit"
            circle
            @click="handleEdit(row)"
          />
          <!-- 删除按钮 -->
          <el-button
            type="danger"
            :icon="Delete"
            circle
            @click="handleDelete(row.commodityId)"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 新增/编辑商品对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="60%">
      <el-form :model="productForm" label-width="100px">
        <el-form-item label="商品图片（第一个文件为封面）">
          <div class="image-upload-container">
            <!-- 显示已上传的图片 -->
            <div class="uploaded-images">
              <img
                v-for="(cover, index) in productForm.imgUrl"
                :key="index"
                :src="cover"
                class="avatar"
              />
            </div>
            <!-- 上传按钮 -->
            <el-upload
              class="avatar-uploader"
              action="http://localhost:8082/Treasure-Pavilion-admin/commodity/uploadAvatar"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :multiple="true"
              accept="image/*"
            >
              <template #trigger>
                <el-icon
                  v-if="productForm.imgUrl.length === 0"
                  class="avatar-uploader-icon"
                  ><Plus
                /></el-icon>
                <span v-else>添加图片</span>
              </template>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="商品标题">
          <el-input v-model="productForm.commodityTitle" />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select
            v-model="productForm.categoryId"
            placeholder="请选择商品分类"
          >
            <!-- 遍历 categoryList 生成选项 -->
            <el-option
              v-for="item in categoryStore.categoryList"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="自定义规格">
          <div class="sku-list">
            <!-- 新增规格输入框，添加滚动样式 -->
            <div
              v-if="productForm.newSpecs.length > 0"
              class="new-sku-specs scrollable"
            >
              <div
                v-for="(spec, index) in productForm.newSpecs"
                :key="index"
                class="new-sku-spec-item"
              >
                <el-input v-model="spec.name" placeholder="规格参数" />
                <!-- 展示 values 中的输入框 -->
                <div
                  v-for="(value, valueIndex) in spec.values"
                  :key="valueIndex"
                >
                  <!-- 添加删除规格值按钮，仅在非第一个规格值时显示 -->
                  <el-button
                    v-if="valueIndex > 0"
                    type="danger"
                    :icon="Delete"
                    circle
                    @click="removeSkuSpec(index, valueIndex)"
                  />
                  <el-input v-model="value.name" placeholder="规格值" />
                </div>
                <el-button type="primary" @click="addSkuSpec(index)"
                  >添加规格值</el-button
                >
              </div>
            </div>
            <el-button type="primary" :icon="Plus" @click="addNewSkuSpec"
              >增加规格</el-button
            >
            <!-- 添加生成 SKU 按钮 -->
            <el-button type="primary" @click="generateSkuList"
              >生成 SKU</el-button
            >
            <!-- 添加表头行 -->
            <div v-if="productForm.skuList.length > 0" class="sku-table-header">
              <span
                v-for="(spec, index) in productForm.newSpecs"
                :key="index"
                style="width: 200px; display: inline-block"
              >
                {{ spec.name }}
              </span>
              <span style="width: 200px; display: inline-block">价格</span>
              <span style="width: 200px; display: inline-block">库存</span>
            </div>
            <!-- 显示生成的 SKU 列表 -->
            <div
              v-for="(sku, index) in productForm.skuList"
              :key="index"
              class="sku-item"
            >
              <el-input
                v-for="(spec, specIndex) in sku.specs"
                :key="specIndex"
                v-model="spec.valueName"
                placeholder="规格值"
                style="width: 200px"
              />
              <el-input
                v-model="sku.price"
                placeholder="价格"
                type="number"
                style="width: 200px"
              />
              <el-input
                v-model="sku.stock"
                placeholder="库存"
                type="number"
                style="width: 200px"
              />
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Search, Delete, Edit } from "@element-plus/icons-vue";
// 引入接口调用方法
import {
  getCommodityListService,
  saveCommodityService,
  deleteCommodityService,
  updateCommodityService,
} from "../api/commodity.js";
import { useCategoryStore } from "../stores/category.js";

// 商品分类
const categoryStore = useCategoryStore();

// 商品列表数据
const tableData = ref([]);

// 分页配置
const pagination = ref({
  current: 1,
  size: 10,
  total: 0,
});

// 搜索表单
const searchForm = ref({
  commodityTitle: null,
  categoryId: null,
  minPrice: null,
  maxPrice: null,
  categoryId: null, // 新增 categoryId 字段
});

// 新增/编辑商品对话框
const dialogVisible = ref(false);
const dialogTitle = ref("新增商品");
// 新增或编辑商品表单数据
const productForm = ref({
  commodityId: null,
  commodityTitle: null,
  categoryId: null,
  commodityPrice: null,
  imgUrl: [],
  skuList: [
    {
      commodityId: null,
      price: null,
      skuId: null,
      specs: [
        {
          name: null,
          valueName: null,
        },
      ],
    },
  ], // 复制 SKU 列表
  newSpecs: [
    {
      name: null,
      values: [
        {
          name: null,
        },
      ],
    },
  ],
});
const isEdit = ref(false);

// 生成 SKU 列表的方法
const generateSkuList = () => {
  const skuList = [];
  const specValues = productForm.value.newSpecs.map((spec) =>
    spec.values.map((value) => value.name)
  );

  // 生成所有可能的组合
  const cartesianProduct = (arr) => {
    if (arr.length === 0) return [[]];
    const head = arr[0];
    const tail = arr.slice(1);
    const tailProduct = cartesianProduct(tail);
    return head.flatMap((x) => tailProduct.map((y) => [x, ...y]));
  };

  const combinations = cartesianProduct(specValues);

  combinations.forEach((combination) => {
    const sku = {
      // 修正引用
      specs: combination.map((value, index) => ({
        name: productForm.value.newSpecs[index].name,
        valueName: value,
      })),
      price: null,
      stock: null,
    };
    skuList.push(sku);
  });

  productForm.value.skuList = skuList;
};

// 增加规格按钮点击事件
const addNewSkuSpec = () => {
  productForm.value.newSpecs.push({
    name: null,
    values: [
      {
        name: null,
      },
    ],
  });
};

// 添加规格值按钮点击事件
const addSkuSpec = (index) => {
  // 修正引用，直接访问 newSpecs 数组元素
  productForm.value.newSpecs[index].values.push({
    name: null,
  });
};

// 处理分页变化
const handlePageChange = (val) => {
  pagination.value.current = val;
  fetchProducts();
};

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pagination.value.size = val;
  fetchProducts();
};

// 搜索商品
const handleSearch = () => {
  pagination.value.current = 1;
  fetchProducts();
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    commodityTitle: null,
    categoryId: null,
    minPrice: null,
    maxPrice: null,
    categoryId: null, // 新增 categoryId 字段
  };
  handleSearch();
};

// 重置productForm
const resetForm = () => {
  productForm.value = {
    commodityId: null,
    commodityTitle: null,
    categoryId: null,
    commodityPrice: null,
    imgUrl: [],
    skuList: [], // 复制 SKU 列表
    newSpecs: [
      {
        name: null,
        values: [
          {
            name: null,
          },
        ],
      },
    ],
  };
};

// 打开新增商品对话框
const handleAdd = () => {
  dialogTitle.value = "新增商品";
  isEdit.value = false;
  // 重置表单
  resetForm();
  dialogVisible.value = true;
};

/**
 * 编辑商品对话框
 */
const handleEdit = (row) => {
  dialogTitle.value = "编辑商品";
  isEdit.value = true;

  productForm.value = {
    commodityId: row.commodityId,
    imgUrl: JSON.parse(JSON.stringify(row.imgUrl)),
    commodityTitle: row.commodityTitle,
    commodityPrice: row.commodityPrice,
    categoryId: row.categoryId,
    skuList: JSON.parse(JSON.stringify(row.skusDOS)),
    newSpecs: JSON.parse(JSON.stringify(row.specsDOS)),
  };
  console.log(productForm.value);
  dialogVisible.value = true;
};

// 删除商品
const handleDelete = (commodityId) => {
  ElMessageBox.confirm("确定要删除该商品吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 这里添加删除商品的接口调用
      let result = deleteCommodityService(commodityId);
      ElMessage.success(result.message);
      fetchProducts();
    })
    .catch(() => {});
};

// 提交表单
const submitForm = async () => {
  // 验证必填字段
  const { commodityTitle, categoryId, skuList } = productForm.value;
  if (!commodityTitle || !categoryId) {
    ElMessage.error("请填写所有必填字段");
    return;
  }
  if (skuList.length === 0) {
    ElMessage.error("请生成 SKU 列表");
    return;
  }

  // 验证每个 SKU 的必填字段
  for (const sku of skuList) {
    const { specs, price, stock } = sku;
    // 验证每个规格是否有未填写的内容
    for (const spec of specs) {
      if (!spec.name || !spec.valueName) {
        ElMessage.error("请填写所有规格必填字段");
        return;
      }
    }
    if (!price || !stock) {
      ElMessage.error("请填写所有 SKU 的必填字段");
      return;
    }
  }
  console.log(productForm.value);
  // 这里添加新增/编辑商品的接口调用
  // 判断是新增还是编辑
  let result;
  if (isEdit.value) {
    // 编辑商品
    result = await updateCommodityService(productForm.value);
  } else {
    result = await saveCommodityService(productForm.value);
  }
  console.log(result);
  ElMessage.success(result.message);
  dialogVisible.value = false;
  fetchProducts();
};

// 获取商品列表
const fetchProducts = async () => {
  try {
    const params = {
      page: pagination.value.page,
      size: pagination.value.size,
      current: pagination.value.current,
      commodityTitle: searchForm.value.keyword,
      minPrice: searchForm.value.minPrice,
      maxPrice: searchForm.value.maxPrice,
      categoryId: searchForm.value.categoryId, // 新增 categoryId 参数
    };
    const result = await getCommodityListService(params);
    tableData.value = result.data.records;
    console.log("返回数据：", tableData.value);
    pagination.value.total = result.data.total;
  } catch (error) {
    ElMessage.error("获取商品列表失败");
  }
};

// 删除规格值按钮点击事件
const removeSkuSpec = (specIndex, valueIndex) => {
  // 修正引用
  productForm.value.newSpecs[specIndex].values.splice(valueIndex, 1);
};

// 处理图片上传成功
const handleUploadSuccess = (response) => {
  // 假设接口返回的图片地址在 response.data.url
  productForm.value.imgUrl.push(response.data);
};

onMounted(() => {
  fetchProducts();
  categoryStore.getCategory();
  console.log("searchFrom数据：", searchForm.value);
  console.log("category数据：", categoryStore.categoryList);
});
</script>

<style scoped>
.products-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

.search-area {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.image-upload-container {
  display: flex;
  align-items: center;
}

.uploaded-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.avatar-uploader {
  margin-left: 20px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar {
  width: 100px;
  height: 100px;
  display: inline-block;
  border-radius: 10%;
  margin-right: 10px;
  margin-bottom: 10px;
}

.sku-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.sku-item {
  display: flex;
  gap: 10px;
  align-items: center;
}

.sku-item .el-input {
  width: 200px;
}

.mx-2 {
  margin: 0 8px;
}

/* 美化搜索区域 */
.search-area {
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.new-sku-specs {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* 新增滚动样式 */
.scrollable {
  max-height: 200px; /* 设置最大高度 */
  overflow-y: auto; /* 超出高度时显示垂直滚动条 */
  border: 1px solid #e4e7ed; /* 可选：添加边框 */
  padding: 10px; /* 可选：添加内边距 */
}

.new-sku-spec-item {
  display: flex;
  flex-wrap: wrap; /* 允许子元素换行 */
  gap: 10px;
  align-items: center;
}

.new-sku-spec-item .el-input {
  width: 200px;
}

/* 调整删除按钮样式 */
.new-sku-spec-item .el-button {
  margin-right: 5px;
}

.sku-table-header {
  display: flex;
  gap: 10px;
  margin-top: 10px;
  font-weight: bold;
}
</style>